package at.ac.tuwien.prog.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.Icon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import at.ac.tuwien.prog.view.controller.FrontController;
import at.ac.tuwien.prog.view.controller.FrontEvent;
import at.ac.tuwien.prog.view.controller.FrontEventType;

/**
 * 
 * @author christoph.pickl@student.tuwien.ac.at
 */
public class MenuBar extends JMenuBar {

	private static final Log LOG = LogFactory.getLog(MenuBar.class);
	
	private static final long serialVersionUID = 6232563848050907905L;
    
	private static final int META_KEY_MASK;
	static {
//		if(System.getProperty("os.name").toLowerCase().contains("mac")) {
//			META_KEY_MASK = KeyEvent.META_MASK;
//		} else {
			META_KEY_MASK = KeyEvent.CTRL_MASK;
//		}
	}
	
	
	public MenuBar(final FrontController controller) {
		final JMenu menuApplication = new JMenu("Application");

		final JMenuItem itemDummy = createMenuItem(menuApplication, 'D', "Dummy Action", KeyEvent.VK_D, META_KEY_MASK, null, FrontEventType.DUMMY, controller);
		final JMenuItem itemQuit = createMenuItem(menuApplication, 'Q', "Quit", KeyEvent.VK_Q, META_KEY_MASK, null, FrontEventType.QUIT, controller);
		
		
		menuApplication.add(itemDummy);
		menuApplication.addSeparator();
		menuApplication.add(itemQuit);
		
		this.add(menuApplication);
	}



    public static JMenuItem createMenuItem(
    		final JMenu menu, final char mnemonicChar, final String label, final int keyCode, final int mask,
    		final Icon icon, final FrontEventType eventType, final FrontController controller) {
        
        if(label == null) throw new NullPointerException("label");

        final JMenuItem item = (icon != null) ? new JMenuItem(label, icon) : new JMenuItem(label);
        
        item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
        	LOG.debug("broadcasting front event with type: " + eventType);
			controller.broadcastEvent(new FrontEvent(item, eventType));
		}});
        
        item.setMnemonic(mnemonicChar);

        if (keyCode != -1) {
            item.setAccelerator(KeyStroke.getKeyStroke(keyCode, mask));
        }

        return item;
    }
}
